<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--分类数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="cateName" placeholder="请输入分类名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="cateOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--产品数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="产品名称" prop="prodName">
                <el-input v-model="queryParams.prodName" placeholder="请输入产品名称" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="产品状态" clearable style="width: 240px">
                  <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:prod:add']">新增</el-button>
              </el-col>
<!--              <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:prod:edit']">修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:prod:remove']">删除</el-button>
              </el-col>-->
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="prodList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="50" align="center"  :show-overflow-tooltip="true"/>
              <el-table-column label="产品编号" align="center" key="prodId" prop="prodId" v-if="columns.prodId.visible" :show-overflow-tooltip="true"/>
              <el-table-column label="产品名称" align="center" key="prodName" prop="prodName" v-if="columns.prodName.visible" :show-overflow-tooltip="true" />
              <el-table-column label="产品分类" align="center" key="cateName" prop="cateName" v-if="columns.cateName.visible" :show-overflow-tooltip="true" />
              <el-table-column label="排序" align="center" key="sort" prop="sort" v-if="columns.sort.visible" :show-overflow-tooltip="true" />
              <el-table-column label="是否上架" align="center" key="status" v-if="columns.status.visible" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns.createTime.visible" width="160">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
                <template slot-scope="scope" v-if="scope.row.userId !== 1">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="preview(scope.row)">预览</el-button>
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']">修改</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品名称" prop="prodName">
              <el-input v-model="form.prodName" placeholder="请输入产品名称" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属分类" prop="cateId">
              <treeselect v-model="cateIds" :options="enabledCateOptions" :multiple="true" :disable-branch-nodes="true" :show-count="true" placeholder="请选择所属分类"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上线状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="列表图(334×250px)">
              <el-upload
                multiple
                :action="uploadImgUrl"
                list-type="picture-card"
                :on-success="handleUploadCateImageSuccess"
                :before-upload="handleCateImageBeforeUpload"
                :limit="limit"
                :on-error="handleCateImageUploadError"
                :on-exceed="handleCateImageExceed"
                ref="imageUpload"
                :on-remove="handleCateImageUploadDelete"
                :show-file-list="true"
                :headers="headers"
                :file-list="imageList"
                :on-preview="handleCateImagePictureCardPreview"
                :class="{hide: this.imageList.length >= this.limit}"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <!-- 上传提示 -->
              <div class="el-upload__tip" slot="tip" v-if="showTip">
                请上传
                <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
                的文件
              </div>
              <el-dialog
                :visible.sync="dialogVisible"
                title="预览"
                width="800"
                append-to-body
              >
                <img
                  :src="dialogImageUrl"
                  style="display: block; max-width: 100%; margin: 0 auto"
                />
              </el-dialog>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="列表样式">
              <el-radio-group v-model="form.prodLabels">
                <el-radio v-for="dict in dict.type.sys_prod_images_style" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品图(高度504px)">
              <el-upload
                multiple
                :action="uploadImgUrl"
                list-type="picture-card"
                :on-success="handleUploadSuccess"
                :before-upload="handleBeforeUpload"
                :limit="limit"
                :on-error="handleUploadError"
                :on-exceed="handleExceed"
                ref="imageUpload"
                :on-remove="handleUploadDelete"
                :show-file-list="true"
                :headers="headers"
                :file-list="fileList"
                :on-preview="handlePictureCardPreview"
                :class="{hide: this.fileList.length >= this.limit}"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <!-- 上传提示 -->
              <div class="el-upload__tip" slot="tip" v-if="showTip">
                请上传
                <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
                的文件
              </div>
              <el-dialog
                :visible.sync="dialogVisible"
                title="预览"
                width="800"
                append-to-body
              >
                <img
                  :src="dialogImageUrl"
                  style="display: block; max-width: 100%; margin: 0 auto"
                />
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="介绍标题">
              <el-input v-model="form.contentTitle" placeholder="请输入介绍标题" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标题Icon">
              <el-upload
                multiple
                :action="uploadImgUrl"
                list-type="picture-card"
                :on-success="handleUploadContentIconSuccess"
                :before-upload="handleContentIconBeforeUpload"
                :limit="limit"
                :on-error="handleContentIconUploadError"
                :on-exceed="handleContentIconExceed"
                ref="imageUpload"
                :on-remove="handleContentIconUploadDelete"
                :show-file-list="true"
                :headers="headers"
                :file-list="contentIconList"
                :on-preview="handlePictureCardPreview"
                :class="{hide: this.contentIconList.length >= this.limit}"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <!-- 上传提示 -->
              <div class="el-upload__tip" slot="tip" v-if="showTip">
                请上传
                <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
                的文件
              </div>
              <el-dialog
                :visible.sync="dialogVisible"
                title="预览"
                width="800"
                append-to-body
              >
                <img
                  :src="dialogImageUrl"
                  style="display: block; max-width: 100%; margin: 0 auto"
                />
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目介绍">
              <editor v-model="form.prodContent" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="参数标题">
              <el-input v-model="form.paramTitle" placeholder="请输入参数标题" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标题Icon">
              <el-upload
                multiple
                :action="uploadImgUrl"
                list-type="picture-card"
                :on-success="handleUploadParamIconSuccess"
                :before-upload="handleParamIconBeforeUpload"
                :limit="limit"
                :on-error="handleParamIconUploadError"
                :on-exceed="handleParamIconExceed"
                ref="imageUpload"
                :on-remove="handleParamIconUploadDelete"
                :show-file-list="true"
                :headers="headers"
                :file-list="paramIconList"
                :on-preview="handlePictureCardPreview"
                :class="{hide: this.paramIconList.length >= this.limit}"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <!-- 上传提示 -->
              <div class="el-upload__tip" slot="tip" v-if="showTip">
                请上传
                <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
                的文件
              </div>
              <el-dialog
                :visible.sync="dialogVisible"
                title="预览"
                width="800"
                append-to-body
              >
                <img
                  :src="dialogImageUrl"
                  style="display: block; max-width: 100%; margin: 0 auto"
                />
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="性能参数">
              <div v-for="(item, index) in params" :key="index">
                <el-input v-model="item.text" placeholder="性能参数" :style="{width:'40%'}" />
                <el-button  @click="removeParamRow(index)" :style="{width:'15%'}">删除</el-button>
              </div>
              <el-button type="primary" @click="addParamRow">+ 新增</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>



<script>
import {listProd, cateTreeSelect, getProd, addProd, updateProd, delProd, changeProdStatus} from "@/api/system/prod"
import {listProdCate} from "@/api/system/prodCate"
import {getSite, getToken} from "@/utils/auth"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import {listToString, splitImages, splitObject} from "@/api/tool/upload";
export default {
  name: "Prod",
  dicts: ['sys_normal_disable','sys_prod_images_style'],
  components: { Treeselect, Splitpanes, Pane },
  props: {
    // 图片数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 50,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      prodList: null,
      // 弹出层标题
      title: "",
      // 所有部门树选项
      cateOptions: undefined,
      prodCateOptions: undefined,
      // 过滤掉已禁用分类树选项
      enabledCateOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 分类名称
      cateName: undefined,
      cateIds: [],
      prodCateName: '',
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        tenantId: getSite(),
        pageNum: 1,
        pageSize: 10,
        prodName: undefined,
        status: undefined,
        cateId: undefined
      },
      // 查询参数
      editQueryParams: {
        tenantId: getSite()
      },
      // 分类数据
      cateData: [],
      //性能参数初始行
      params: [{
        text: '',
      }],
      // 列信息
      columns: {
        prodId: { label: '产品编号', visible: true },
        prodName: { label: '产品名称', visible: true },
        cateName: { label: '产品分类', visible: true },
        sort: { label: '排序', visible: true },
        status: { label: '是否上架', visible: true },
        createTime: { label: '创建时间', visible: true }
      },
      // 表单校验
      rules: {
        prodName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        /*cateIds: [
          { required: true, message: "分类不能为空", trigger: "blur" }
        ],*/
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ]
      },
      // 上传的图片服务器地址
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // 上传图片个数
      number: 0,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      previewUrl: process.env.VUE_APP_PROD_URL,
      fileList: [],   //产品图
      imageList: [],  //列表缩略图
      contentIconList: [], //介绍icon
      paramIconList: [],  //参数icon
      uploadList: [], //临时上传列表
      dialogVisible: false,
      dialogImageUrl: "",
    }
  },
  watch: {
    // 根据名称筛选部门树
    cateName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getCateTree()
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    /** 查询产品列表 */
    getList() {
      this.loading = true
      listProd(this.queryParams).then(response => {
          this.prodList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    /** 查询分类下拉树结构 */
    getCateTree() {
      cateTreeSelect(this.editQueryParams).then(response => {
        this.cateOptions = response.data
        this.enabledCateOptions = this.filterDisabledCate(JSON.parse(JSON.stringify(response.data)))
      });
      listProdCate(this.editQueryParams).then(response => {
        this.prodCateOptions = response.data;
      })
    },
    // 过滤禁用的分类
    filterDisabledCate(cateList) {
      return cateList.filter(cate => {
        if (cate.disabled) {
          return false
        }
        if (cate.children && cate.children.length) {
          cate.children = this.filterDisabledCate(cate.children)
        }
        return true
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.cateId = data.id
      this.handleQuery()
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用"
      this.$modal.confirm('确认要' + text + '"' + row.prodName + '"的产品吗？').then(function() {
        return changeProdStatus(row.prodId, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + "成功")
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0"
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        prodId: undefined,
        cateId: undefined,
        prodName: undefined,
        status: "0",
        prodContent: undefined,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.queryParams.deptId = undefined
      this.$refs.tree.setCurrentKey(null)
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加产品"
      //产品图
      this.fileList = [];
      //列表缩略图
      this.imageList = [];
      //分类数据
      this.cateData = [];
      this.cateIds = [];
      //性能参数
      this.params = [];
      //介绍icon
      this.contentIconList = [];
      //参数icon
      this.paramIconList = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const prodId = row.prodId
      getProd(prodId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改产品"
        //产品图
        this.fileList = [];
        if(this.form.prodImage){
          const imageArr = this.form.prodImage.split(';');
          for (var i = 0; i < imageArr.length; i++) {
            this.fileList.push({ name: imageArr[i], fileName: imageArr[i],url: process.env.VUE_APP_BASE_API + imageArr[i] });
          }
        }
        //分类数据
        this.cateData = [];
        this.cateIds = [];
        if(this.form.cateId){
          const cateArr = JSON.parse(this.form.cateId);
          for (var i = 0; i < cateArr.length; i++) {
            this.cateIds.push(cateArr[i].id);
          }
        }
        //列表缩略图
        this.imageList = [];
        if(this.form.prodThum){
          const imageArr = this.form.prodThum.split(';');
          for (var i = 0; i < imageArr.length; i++) {
            this.imageList.push({ name: imageArr[i], fileName: imageArr[i],url: process.env.VUE_APP_BASE_API + imageArr[i] });
          }
        }
        //介绍icon
        this.contentIconList = [];
        if(this.form.contentIcon){
          const imageArr = this.form.contentIcon.split(';');
          for (var i = 0; i < imageArr.length; i++) {
            this.contentIconList.push({ name: imageArr[i], fileName: imageArr[i],url: process.env.VUE_APP_BASE_API + imageArr[i] });
          }
        }
        //参数icon
        this.paramIconList = [];
        if(this.form.paramIcon){
          const imageArr = this.form.paramIcon.split(';');
          for (var i = 0; i < imageArr.length; i++) {
            this.paramIconList.push({ name: imageArr[i], fileName: imageArr[i],url: process.env.VUE_APP_BASE_API + imageArr[i] });
          }
        }
        //性能参数
        this.params = [];
        if(this.form.prodParam){
          this.params = JSON.parse(this.form.prodParam);
        }
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 租户ID
          this.form.tenantId = getSite();
          // 产品图
          this.form.prodImage = splitImages(this.fileList);
          // 列表缩略图
          this.form.prodThum = splitImages(this.imageList);
          //性能参数
          this.form.prodParam = JSON.stringify(this.params);
          //介绍icon
          this.form.contentIcon = splitImages(this.contentIconList);
          //参数Icon
          this.form.paramIcon = splitImages(this.paramIconList);
          const content = this.form.prodContent;
          this.form.prodContent = btoa(unescape(encodeURIComponent(content)));
          //父级分类
          this.form.cateId = JSON.stringify(this.selectedLabels());
          let thatProdCateName = '';
          if(this.prodCateName.length > 0){
            thatProdCateName = this.prodCateName.substring(0,this.prodCateName.length-1);
          }
          this.form.cateName = thatProdCateName;
          if(JSON.parse(this.form.cateId).length == 0){
            this.$modal.confirm('当前信息未选择分类，是否确认提交？').then(function() {
              if (this.form.prodId != undefined) {
                return updateProd(this.form);
              }else{
                return addProd(this.form);
              }
            }).then(() => {
              this.open = false
              this.getList()
            }).catch(() => {})
          }else{
            if (this.form.prodId != undefined) {
              updateProd(this.form).then(response => {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                this.getList()
              })
            } else {
              addProd(this.form).then(response => {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getList()
              })
            }
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const prodId = row.prodId
      this.$modal.confirm('是否确认删除名称为"' + row.prodName + '"的数据项？').then(function() {
        return delProd(prodId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    selectedLabels() {
      const labels = []
      const findLabels = (nodes, ids) => {
        ids.forEach(id =>{
          nodes.forEach(node => {
            if(node.prodCateId == id){
              labels.push({id: node.prodCateId,label: node.prodCateName})
              this.prodCateName += node.prodCateName + ',';
            }
          })
        })
      }
      findLabels(this.prodCateOptions, this.cateIds)
      return labels;
    },
    /**产品预览 **/
    preview(row){
      const cateArr = JSON.parse(row.cateId);
      if(cateArr.length > 0){
        const url = this.previewUrl.replace('#{cateId}',cateArr[0].id).replace('#{prodId}',row.prodId);
        window.open(url);
      }

    },
    //性能参数
    addParamRow() {
      this.params.push({ text: '' }); // 添加新行
    },
    removeParamRow(index) {
      this.params.splice(index, 1); // 删除指定行
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.newFileName, fileName: res.fileName,url: res.url });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", listToString(this.baseUrl,this.fileList));
        this.$modal.closeLoading();
      }
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 删除图片
    handleUploadDelete(file) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.fileList.splice(findex, 1);
        this.$emit("input", listToString(this.baseUrl,this.fileList));
      }
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    //分类图片方法
    // 上传前loading加载
    handleCateImageBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 上传成功回调
    handleUploadCateImageSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.newFileName, fileName: res.fileName,url: res.url });
        this.uploadedCateImageSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedCateImageSuccessfully();
      }
    },
    // 上传结束处理
    uploadedCateImageSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.imageList = this.imageList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", listToString(this.baseUrl,this.imageList));
        this.$modal.closeLoading();
      }
    },
    // 文件个数超出
    handleCateImageExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleCateImageUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 删除图片
    handleCateImageUploadDelete(file) {
      const findex = this.imageList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.imageList.splice(findex, 1);
        this.$emit("input", listToString(this.baseUrl,this.imageList));
      }
    },
    // 预览
    handleCateImagePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //介绍ICON图片上传
    // 上传前loading加载
    handleContentIconBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 上传成功回调
    handleUploadContentIconSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.newFileName, fileName: res.fileName,url: res.url });
        this.uploadedContentIconSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedContentIconSuccessfully();
      }
    },
    // 上传结束处理
    uploadedContentIconSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.contentIconList = this.contentIconList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", listToString(this.baseUrl,this.contentIconList));
        this.$modal.closeLoading();
      }
    },
    // 文件个数超出
    handleContentIconExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleContentIconUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 删除图片
    handleContentIconUploadDelete(file) {
      const findex = this.contentIconList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.contentIconList.splice(findex, 1);
        this.$emit("input", listToString(this.baseUrl,this.contentIconList));
      }
    },
    //标题ICON
    // 上传前loading加载
    handleParamIconBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 上传成功回调
    handleUploadParamIconSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.newFileName, fileName: res.fileName,url: res.url });
        this.uploadedParamIconSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedParamIconSuccessfully();
      }
    },
    // 上传结束处理
    uploadedParamIconSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.paramIconList = this.paramIconList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", listToString(this.baseUrl,this.paramIconList));
        this.$modal.closeLoading();
      }
    },
    // 文件个数超出
    handleParamIconExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleParamIconUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 删除图片
    handleParamIconUploadDelete(file) {
      const findex = this.paramIconList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.paramIconList.splice(findex, 1);
        this.$emit("input", listToString(this.baseUrl,this.paramIconList));
      }
    },
  }
}
</script>
